//
//  BuyOrderContentViewController.m
//  quxiangtao
//
//  Created by xbmios on 2018/7/17.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "BuyOrderContentViewController.h"
#import "BuyOrderTableViewCell.h"

#import "BuyOrderContentDetailViewController.h"

#import "BuyOrderContentModel.h"

static NSString *buyGoodsCellID = @"buyGoodsCellID";

@interface BuyOrderContentViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) UITableView *gooodsTableView;

@property (assign, nonatomic) NSInteger page;

@property (strong, nonatomic) NSMutableArray *orderArr;

@end

@implementation BuyOrderContentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = WhiteColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.page = 1;
    
    [self.view addSubview:self.gooodsTableView];
    __weak typeof(self) weakSelf = self;
    [self.gooodsTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.view.mas_top);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom);
    }];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [header beginRefreshing];
    [header setTitle:@"下拉可以刷新!" forState:MJRefreshStateIdle];
    [header setTitle:@"松手立即刷新!" forState:MJRefreshStatePulling];
    [header setTitle:@"正在加载..." forState:MJRefreshStateRefreshing];
    header.stateLabel.font = Font(24);
    header.backgroundColor = [UIColor clearColor];
    [header setTintColor:[UIColor clearColor]];

    header.stateLabel.textColor = Color999999;
    header.lastUpdatedTimeLabel.hidden = YES;
    self.gooodsTableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在加载。。。。" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多数据！" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = Font(17);
    footer.stateLabel.textColor = Color999999;
    self.gooodsTableView.mj_footer = footer;
    self.gooodsTableView.mj_footer.hidden = NO;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goodsConfirmReceipt:) name:@"NSConfirmReceiptNotification" object:nil];
}

- (void)goodsConfirmReceipt:(NSNotification *)notification {
    
    NSDictionary *dict = notification.object;
    
    [self.orderArr removeObject:dict[@"model"]];
    
    [self.gooodsTableView reloadData];
    
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark 下拉刷新数据
- (void)loadNewData
{
    
    self.page = 1;
    
    [self.gooodsTableView.mj_footer resetNoMoreData];
    [self loadData];
    
    [self.gooodsTableView reloadData];
    
    // 拿到当前的下拉刷新控件，结束刷新状态
    [self.gooodsTableView.mj_header endRefreshing];
    
}

- (void)loadMoreData {
    
    self.page ++;

    [self loadData];
    // 刷新表格
    [self.gooodsTableView reloadData];
    // 拿到当前的上拉刷新控件，结束刷新状态
    [self.gooodsTableView.mj_footer endRefreshing];

}

- (void)loadData {
    self.gooodsTableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"noData"
                                                                  titleStr:@"暂无数据"
                                                                 detailStr:@""];
    __weak typeof(self) weakSelf = self;
    
    [BuyOrderContentModel buyOrderContentModelWithPage:self.page buyType:self.tradeType successBlock:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            NSArray *arr = responseObject[@"data"];
            
            if (arr.count > 0 || weakSelf.orderArr.count > 0 ) {
                
                weakSelf.gooodsTableView.hidden = NO;
                
                if (self.page == 1) {
                    
                    weakSelf.orderArr = (NSMutableArray *)arr;
                    
                }else {
                    
                    [weakSelf.orderArr addObjectsFromArray:arr];
                    
                }
                
                [weakSelf.gooodsTableView reloadData];
                
                if (self.page > 1 && arr.count == 0) {
                    
                    [self.gooodsTableView.mj_footer endRefreshingWithNoMoreData];
                }
                
                // 滚动cell
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:(self.page - 1) * 10];
                
                [weakSelf.gooodsTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
                
            }else {
                
                weakSelf.gooodsTableView.hidden = YES;
                
                //                weakSelf.tipView.hidden = NO;
                
                //                weakSelf.tipView = [[TipView alloc] initWithImage:@"wujilu2" andText:@"暂无奖励" showButton:NO andBtnAction:nil];
                //                weakSelf.tipView.frame = self.view.bounds;
                
                //                [weakSelf.view addSubview:weakSelf.tipView];
                
            }
            
        }else  {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
            
        }

        
    } failBlock:^(NSError *error) {
        
        if (error) {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
        }
    }];
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return jisuan(370);
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BuyOrderContentModel *model = self.orderArr[indexPath.row];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    if ([self.tradeType intValue] == 5 ) {
        if (![model.spid isEqualToString:@""]) {
            WebViewController *vc = [[WebViewController alloc] init];
            vc.title = @"点击晒图";
            vc.url = [NSString stringWithFormat:@"%@%@?ddid=%@&where=pintuan&spellid=%@&userid=%@", ebaseH5,@"blueprint.html", model.ddid, model.spid,[CommonUserInfo sharedInstance].user_id];
            //[RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey]
            
            if (vc) {
                [self.navigationController pushViewController:vc animated:YES];
            }
        }else if (![model.bargain_id isEqualToString:@""]){
            WebViewController *vc = [[WebViewController alloc] init];
            vc.title = @"点击晒图";
            vc.url = [NSString stringWithFormat:@"%@%@?ddid=%@&where=bargain&bargain_id=%@&userid=%@", ebaseH5,@"blueprint.html", model.ddid, model.bargain_id,[CommonUserInfo sharedInstance].user_id];
            //[RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey]
            
            if (vc) {
                [self.navigationController pushViewController:vc animated:YES];
            }
            
        }
        
    }
//    BuyOrderContentDetailViewController *detailVC = [[BuyOrderContentDetailViewController alloc] init];
////    detailVC.tradeType = self.tradeType;
//    [self.navigationController pushViewController:detailVC animated:YES];
    
}

#pragma mark -delegate\datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.orderArr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BuyOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:buyGoodsCellID];
    
    if (!cell) {
        
        cell = [[BuyOrderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:buyGoodsCellID];
        
    }
    
    cell.parentVC = self;
    
    cell.type = [self.tradeType integerValue];
    
    cell.orderModel = self.orderArr[indexPath.row];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
}

#pragma mark -lazy
- (UITableView *)gooodsTableView {
    
    if (!_gooodsTableView) {
        
        _gooodsTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        
        _gooodsTableView.delegate = self;
        _gooodsTableView.dataSource = self;
        
        _gooodsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        _gooodsTableView.showsVerticalScrollIndicator = NO;
        _gooodsTableView.showsHorizontalScrollIndicator = NO;
        
        _gooodsTableView.estimatedSectionHeaderHeight = 0;
        _gooodsTableView.estimatedSectionFooterHeight = 0;
        _gooodsTableView.estimatedRowHeight = 0;
        
        if (@available(iOS 11.0, *)) {
            
            _gooodsTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            
        }
        
    }
    
    return _gooodsTableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
